<template>
  <div class="list-setting-container">
    <SectionTitle :is-dot="showDot" title="数据表管理">
      <span class="title-tip">(同步字段名为统计图表实际展示字段名，选中字段同步后即可在统计图表进行图表配置)</span>
      <PlainCreateBtn @click="addDataForm">添加数据表</PlainCreateBtn>
    </SectionTitle>
    <template v-if="dataForms && dataForms.length">
      <div v-for="formItem in dataForms" :key="formItem.reportKey" class="form-item">
        <div class="form-header">
          <span class="red-text">*</span><span class="form-name">数据表名称</span>
          <el-input v-model="formItem.reportName" type="text" maxlength="50" placeholder="请输入" size="small" class="width240 input"/>
          <div v-if="formItem.listData && formItem.listData.length > 1" class="flex-center ml12">
            <span class="red-text">*</span><span class="form-name">主子表单</span>
            <selectWithoutHttp v-model="formItem.mainFormKey" :list-data="formItem.listData" filterable class="select width240" label-name="name" key-name="key" placeholder="请选择" />
          </div>
          <div>
            <div v-if="canSync(formItem)" class="flex-center"><span class="sync-text" @click="syncData(formItem)">立即同步数据</span><img :src="syncIcon" alt=""></div>
            <el-tooltip v-else :open-delay="800">
              <div slot="content" style="max-width:200px;">{{ inSync(formItem)?'数据同步中，可刷新查看同步状态':'列表没有选中字段，无法同步' }}</div>
              <div v-if="inSync(formItem)" class="sync-text-disable"><span>数据同步中</span><i class="el-icon-loading icon"/></div>
              <div v-else class="sync-text-disable"><span>立即同步数据</span><img :src="syncIcon" alt=""></div>
            </el-tooltip>
          </div>
          <div class="btn-wrap">
            <img :src="copyIcon" class="icon" alt="复制" @click.stop="copyForm(formItem)">
            <img :src="deleteIcon" class="icon" alt="删除" @click.stop="delForm(formItem.reportKey)">
          </div>
        </div>
        <dataFormGraggable ref="listSettingRef" v-model="formItem.fields" @getCurSelectedNum="getCurSelectedNum" @setListData="setListData(formItem.reportKey)" @setName="setName($event,formItem.reportKey)"/>
      </div>
    </template>
    <EmptyPlaceholder v-else :empty-text-top="0" text="暂无数据表" />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import dataFormGraggable from './module/dataFormGraggable';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { forEachFormOptions } from '@/utils/formMakeUtils.js';
import { dataFieldTargets } from './settingTargets';
import { showModal } from '@/utils/message';
import copyIcon from '@/assets/auditProcess/copy_form.png';
import deleteIcon from '@/assets/auditProcess/delete_form.png';
import syncIcon from '@/assets/auditProcess/sync.png';
import { generateUUID } from '@/utils/tools';
export default {
  name: 'DataSetting',
  components: {
    SectionTitle,
    EmptyPlaceholder,
    dataFormGraggable,
    selectWithoutHttp
  },
  props: {
    formList: {
      type: Array,
      default: () => []
    },
    syncStatus: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      syncIcon,
      copyIcon,
      deleteIcon,
      dataStatus: false,
      dataForms: [],
      listFields: []
    };
  },
  computed: {
    showDot() {
      if (!this.dataForms || (this.dataForms && this.dataForms.length === 0)) return false;
      return !this.dataStatus;
    }
  },
  watch: {
    dataForms: {
      handler() {
        this.statusCheck();
      },
      deep: true
    }
  },
  created() {
    this.statusCheck();
  },
  methods: {
    // 初始化字段列表
    initList(formList) {
      this.listFields = [];
      forEachFormOptions(formList, item => {
        if (dataFieldTargets.includes(item.type)) { // 统计字段单独处理
          const statisticsType = ['linkForm'];
          if (statisticsType.includes(item.type)) {
            const { statistics } = item.options;
            if (statistics && statistics.length) {
              statistics.forEach(key => {
                const findIndex = item.subform.findIndex(subItem => subItem.key === key);
                findIndex !== -1 && this.listFields.push({ isCheck: false, ...item.subform[findIndex], isStatistics: true });
              });
            }
          } else {
            this.listFields.push({ isCheck: false, ...item, isStatistics: false });
          }
        }
      });
      this.listFields = this.listFields.filter(el => { // 隐藏加密字段
        if (el.options) {
          return !el.options.isSecret;
        }
        return true;
      });
      this.initDataForm();
    },
    // 回填数据表
    initDataForm() {
      if (!this.dataForms) return;
      const initFields = this.initFields() || [];
      this.dataForms.map(i => {
        const fields = JSON.parse(JSON.stringify(initFields));// 进行深拷贝
        const listData = [];
        const isCheckFields = i.fields.filter(j => j.isCheck);
        fields.map(k => {
          if (!k.isCheck && isCheckFields.find(i => i.name === k.name)) {
            k.disable = true;
          } else {
            k.disable = false;
          }
        });
        i.fields.map(j => {
          if (!j.isCheck && isCheckFields.find(i => i.name === j.name)) {
            j.disable = true;
          } else {
            j.disable = false;
          }
          const index = fields.findIndex(k => k.key === j.key);
          if (index !== -1) {
            if (fields[index].isSubTable && j.isCheck) {
              const subformItem = this.formList.find(el => fields[index].linkFormKey === el.key);
              if (!listData.find(j => subformItem.key === j.key)) {
                listData.push({
                  key: subformItem.key,
                  name: subformItem.name
                });
              }
            }
            // 原有字段部分属性不可更新
            const { isCheck, disable, name } = j;
            fields[index] = Object.assign(fields[index], { isCheck, disable, name });
          }
        });
        this.$set(i, 'fields', fields);
        this.$set(i, 'listData', listData);
      });
    },
    statusCheck() {
      this.dataStatus = this.validate();
      this.$emit('statusCheck');
    },
    validate() {
      if (!this.dataForms) return true;
      let valid = true;
      this.dataForms.find(i => {
        if (!i.reportName || (!i.mainFormKey && i.listData && i.listData.length > 1)) {
          valid = false;
        }
        // 是否勾选同步字段
        const selectNum = i.fields.reduce((pre, curr) => pre + (curr['isCheck'] ? 1 : 0), 0);
        if (selectNum < 1) {
          valid = false;
        }
      });
      return valid;
    },
    // 校验表单
    validateForm() {
      return new Promise((resolve, reject) => {
        this.dataForms.find(i => {
          if (!i.reportName || (!i.mainFormKey && i.listData && i.listData.length > 1)) {
            reject('请检查高级设置-数据同步信息是否填写完整');
            return;
          }
          if (this.dataForms.filter(j => j.reportKey !== i.reportKey).find(k => k.reportName === i.reportName)) {
            reject(`【${i.reportName}数据表】名称与其他数据表名称重复，请调整后再保存`);
            return;
          }
          // 是否勾选同步字段
          const selectNum = i.fields.reduce((pre, curr) => pre + (curr['isCheck'] ? 1 : 0), 0);
          if (selectNum < 1) {
            reject('请勾选高级设置-数据同步所需同步字段');
            return;
          }
        });
        resolve(true);
      });
    },
    setData(dataForms = []) {
      this.dataForms = dataForms || [];
    },
    getData() {
      const data = JSON.parse(JSON.stringify(this.dataForms));
      // 当只勾选一个子表单的字段，默认主子表单为当前勾选
      data.map(i => {
        if (i.listData && i.listData.length === 1) {
          i.mainFormKey = i.listData[0].key;
        }
        i.fields.map((j, index) => {
          const { name, realName, key, linkFormKey, isCheck, disable, isStatistics } = j;
          i.fields[index] = { name, realName, key, linkFormKey, isCheck, disable, isStatistics };
        });
      });
      return data;
    },
    addDataForm() {
      const fields = this.initFields();
      this.dataForms.push({
        reportKey: generateUUID(),
        reportName: '',
        mainFormKey: '',
        fields,
        listData: []
      });
      this.statusCheck();
    },
    copyForm(item) {
      const copyItem = JSON.parse(JSON.stringify(item));
      delete copyItem.reportKey;
      copyItem.reportName = copyItem.reportName + '副本1';
      this.dataForms.push({
        reportKey: generateUUID(),
        ...copyItem
      });
    },
    delForm(reportKey) {
      showModal('请确认是否删除该表，删除后配置的图表将不展示任何数据', '', {
        customClass: 'del-message del-message-cancel'
      }).then(_ => {
        const findIndex = this.dataForms.findIndex(el => el.reportKey === reportKey);
        this.dataForms.splice(findIndex, 1);
      });
    },
    getCurSelectedNum(length) {
      this.dataStatus < 1;
      this.$emit('statusCheck');
      return !!length;
    },
    initFields() {
      const fields = JSON.parse(JSON.stringify(this.listFields));
      fields.map(el => {
        el.realName = el.name;
        if (el.isSubTable || el.linkFormKey) {
          const subformItem = this.formList.find(j => el.linkFormKey === j.key);
          if (subformItem) {
            el.realName = subformItem.name + '.' + el.name;
          }
        }
      });
      return fields;
    },
    // 同名字段禁用
    setFieldDisable(reportKey) {
      const index = this.dataForms.findIndex(el => el.reportKey === reportKey);
      const isCheckFields = this.dataForms[index].fields.filter(j => j.isCheck);
      this.dataForms[index].fields.map(el => {
        if (!el.isCheck && isCheckFields.find(j => j.name === el.name)) {
          el.disable = true;
        } else {
          el.disable = false;
        }
      });
    },
    // 获取主子表单列表
    setListData(reportKey) {
      const index = this.dataForms.findIndex(el => el.reportKey === reportKey);
      const listData = [];
      this.setFieldDisable(reportKey);
      this.dataForms[index].fields.map(el => {
        if (el.isSubTable && el.isCheck) {
          const subformItem = this.formList.find(j => el.linkFormKey === j.key);
          if (!listData.find(j => subformItem.key === j.key)) {
            listData.push({
              key: subformItem.key,
              name: subformItem.name
            });
          }
        }
      });
      this.$set(this.dataForms[index], 'listData', listData);
    },
    setName(e, reportKey) {
      this.setFieldDisable(reportKey);
    },
    canSync(formItem) {
      return !this.inSync(formItem) && formItem.fields.filter(i => i.isCheck).length > 0;
    },
    inSync(formItem) {
      const syncItem = this.syncStatus.find(i => i.reportKey === formItem.reportKey);
      return syncItem && syncItem.inSync;
    },
    syncData(formItem) {
      if (!formItem.reportName) {
        this.$message.error('请填写数据表名称');
        return;
      }
      showModal('请确认是否保存数据表勾选内容及立即执行同步数据', '', {
        confirmButtonText: '保存及执行同步',
        customClass: 'del-message del-message-cancel field-message'
      }).then(_ => {
        const { reportKey } = formItem;
        this.$emit('syncData', { reportKey });
      });
    }
  }
};
</script>

<style scoped lang="scss">
.list-setting-container {
  .title-tip {
    flex: 1;
    font-size: 14px;
    color: #999;
    font-weight: normal;
    margin-left: 6px;
  }
  .fields-checkbox {
    margin-left: 6px;
    & ::v-deep {
      .el-checkbox__label {
        font-size: 12px;
        padding-left: 4px;
      }
      .el-checkbox {
        color: #333;
      }
    }
  }
  .form-item{
    margin: 16px 0 20px;
    .form-name {
      font-size: 14px;
      color: #666666;
      margin-right: 12px;
    }
  }
  .form-header {
    display: flex;
    align-items: center;
    background: #F8F8F9;
    padding: 12px 16px;
    .red-text {
      color: red;
      margin-right: 2px;
    }
    .input, .select {
      margin-right: 12px;
    }
    img {
      width: 14px;
      height: 14px;
      margin-left: 4px;
    }
    .btn-wrap {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .sync-text {
      font-size: 14px;
      color: #406EFF;
      cursor: pointer;
    }
    .sync-text-disable {
      display: flex;
      align-items: center;
      opacity: .5;
      font-size: 14px;
      color: #406EFF;
      margin-right: 4px;
      .icon {
        background: transparent;
        color: #406EFF;
        margin: 0;
      }
    }
    .icon {
      margin-left: 12px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background: #fff;
    }
    .width120{
      width: 120px;
      &::v-deep {
        .el-input__inner {
          width: 120px !important;
        }
      }
    }
    .width240{
      width: 240px;
      &::v-deep {
        .el-input__inner {
          width: 240px !important;
        }
      }
    }
  }
}
</style>
<style lang="scss">
  .field-message .el-message-box__btns .el-button--default:first-child {
    margin-right: -222px;
  }
  .field-message {
    .el-message-box__btns {
      padding-left: 66px;
    }
  }
</style>
